from django.shortcuts import render, redirect
from web.forms.wiki import WikiModelForm
from django.urls import reverse
from web import models
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from utils.encrypt import uid
from utils.tencent.cos import upload_file

def wiki(request, project_id):
    """wiki首页展示"""
    wiki_id = request.GET.get("wiki_id")
    # 判断wiki_id是否存在或者是否是十进制的小数，如果是则返回wiki首页
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, "wiki.html")
    if wiki_id:
        # 如果存在wiki_id说明在访问详细页，去表中获取详细页信息
        wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
        return render(request, "wiki.html", {"wiki_object": wiki_object})
    # 如果不存在wiki_id则返回wiki首页
    return render(request, "wiki.html")


def wiki_add(request, project_id):
    """wiki添加功能, 通过modelForm实现"""
    if request.method == "GET":
        form = WikiModelForm(request)
        return render(request, "wiki_form.html", {"form": form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 保存之前，将project字段添加上
        form.instance.project = request.tracer.project
        # 判断用户是否已经选择了父文章, 如果选择了文章，就把自己的深度+1
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth
        else:
            form.instance.depth = 1
        form.save()
        url = reverse("web:manage:wiki", kwargs={"project_id": project_id})
        return redirect(url)
    return render(request, "wiki_form.html", {"form": form})

def wiki_catalog(request, project_id):
    """wiki目录"""
    data = models.Wiki.objects.filter(project_id=project_id).values("id", "title", "parent").order_by("depth", "id")
    return JsonResponse({"status": True, "data": list(data)})


def wiki_delete(request, project_id, wiki_id):
    """删除wiki"""
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    url = reverse("web:manage:wiki", kwargs={"project_id": project_id})
    return redirect(url)

def wiki_edit(request, project_id, wiki_id):
    """编辑文章"""
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse("web:manage:wiki", kwargs={"project_id": project_id})
        return redirect(url)
    if request.method == "GET":
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, "wiki_form.html", {"form": form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        # 保存之前，将project字段添加上
        form.instance.project = request.tracer.project
        # 判断用户是否已经选择了父文章, 如果选择了文章，就把自己的深度+1
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth
        else:
            form.instance.depth = 1
        form.save()
        # 保存成功跳转到当前编辑的页面
        url = reverse("web:manage:wiki", kwargs={"project_id": project_id})
        preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(preview_url)
    return render(request, "wiki_form.html", {"form": form})


@csrf_exempt   # 免除csrf token
def wiki_upload(request, project_id):
    """markdown 插件上传图片"""
    # print("收到上传图潘了")
    result = {
        "success": 0,
        "message": None,
        "url": None,
    }
    print(request.FILES)  # <MultiValueDict: {'editormd-image-file': [<TemporaryUploadedFile: IMG_20201010_214105.jpg (image/jpeg)>]}>
    image_object = request.FILES.get("editormd-image-file")  # 拿到文件对象
    if not image_object:
        result["message"] = "文件不存在"
        return JsonResponse(result)

    # 需要把文件对象，上传到当前项目的桶中
    ext = image_object.name.rsplit(".")[-1]  # 拿到图片文件的后缀名
    # 图片名称
    key = "{}.{}".format(uid(request.tracer.user.mobile_phone), ext)

    # 上传图片
    image_url = upload_file(request.tracer.project.bucket,
                request.tracer.project.region,
                image_object,
                key
                )
    # 拿到腾讯云存储上的图片的url
    print(image_url)
    # 上传成功之后，还需要通知以下markdown组件
    result["success"] = 1
    result["url"] = image_url
    return JsonResponse(result)


